﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LEV_ST_OneWireDataResolution;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Bson;
using System.IO;
using System.Reflection;

//image 210K
//json 288076, Bson 216101
//image 1.4M
//json 1964776, Bson 1473626

//Struct
//json 492, Bson 598

namespace LEV_Applications
{
    public partial class LEVAppForm : Form
    {
        public LEVAppForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.textBox2.Text = LEVUtilityLibrary.SecurityCryptography.AesCrypto.EncryptBase64(this.textBox1.Text);
            //this.textBox2.Text = LEV_CryptoLibrary.AESCrypto.AesEncryptBase64(this.textBox1.Text);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.textBox3.Text = LEVUtilityLibrary.SecurityCryptography.AesCrypto.DecryptBase64(this.textBox2.Text);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";

        }
        public enum t1
        {
            Cmd_Set_DSG_Load_Gate = (0x70),
            Cmd_Set_CHG_Shiftet_Gate = (0x71),
            Cmd_Set_ADC_VPC_Gate = (0x72),
            Cmd_Set_ADC_VPD_Gate = (0x73)
        }

        public enum t2
        {
            Cmd_Communi_Multiplex_Reset = (0x80),
            Cmd_Communi_Multiplex_Set_Channel = (0x81),
            Cmd_UART_Set_Baud_Rate = (0x82),
            Cmd_UART_Set_Default_Baud_Rate = (0x83),
            Cmd_UART_RS485_Enable = (0x84),
            Cmd_UART_RS485_Disable = (0x85),
            Cmd_One_Wire_Commu_Enable = (0x86),
            Cmd_One_Wire_Commu_Disable = (0x87),
            Cmd_I2C_Reset = (0x88),  //no used on Ver 2.0
            Cmd_I2C_Set_Address = (0x89),  //no used on Ver 2.0
        }
        private void button5_Click(object sender, EventArgs e)
        {
                textBox5.AppendText("enum = " + ((t1)0x83).ToString() + Environment.NewLine);
                textBox5.AppendText("enum = " + ((t2)0x83).ToString() + Environment.NewLine);
                textBox5.AppendText("enum = " + Enum.IsDefined(typeof(t1),0x83)  + Environment.NewLine);
                textBox5.AppendText("enum = " + Enum.IsDefined(typeof(t2),0x83)  + Environment.NewLine);

            if (!textBox4.Text.Equals(string.Empty))
            {
                string temp = LEVUtilityLibrary.MassUtilities.StringTrim_Replace_EnterAndTab_CombineMultiSpaceToOne(textBox4.Text);
                textBox5.AppendText("temp = " + temp + Environment.NewLine);
                byte[] array = LEVUtilityLibrary.MassUtilities.HexStringToByteArray(temp);
                byte[] unpacking;
                int st,ed,dst,ded;
                LEVUtilityLibrary.BatteryPack_OneWirePacketFormat.OneWireDataGroup group = LEVUtilityLibrary.BatteryPack_OneWirePacketFormat.UnPacking(array, out unpacking, out st, out ed, out dst, out ded);
                string data = LEVUtilityLibrary.MassUtilities.ByteArrayToHexString(unpacking, true);
                textBox5.AppendText("group = " + group + Environment.NewLine);
                textBox5.AppendText("start idx = " + st + Environment.NewLine);
                textBox5.AppendText("end idx = " + ed + Environment.NewLine);
                textBox5.AppendText("data start idx = " + dst + Environment.NewLine);
                textBox5.AppendText("data end idx = " + ded + Environment.NewLine);
                textBox5.AppendText("data = " + data + Environment.NewLine);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            byte[] temp;
            //temp = B2BToolKitControl.CommandProvider.SendingCmdToB2BToolKit<B2BToolKitControl.Cmd_ToolKitDataTransmit>(B2BToolKitControl.Cmd_ToolKitDataTransmit.Cmd_UART_RS485_Transmit_Data, new byte[] { 0x00 });
            //temp = B2BToolKitControl.CommandProvider.SendingCmdToB2BToolKit(B2BToolKitControl.Cmd_ToolKitDataTransmit.Cmd_UART_RS485_Transmit_Data, new byte[] { 0x00 });
            //temp = B2BToolKitControl.CommandProvider.SendingCmdToLevBatteryViaB2BToolKit<LEVBatteryPackControl.Cmd_Battery_SetInfor>(LEVBatteryPackControl.Cmd_Battery_SetInfor.Cmd_SetOneWireTransmitOnce, new byte[] { 0x01 });
            //temp = B2BToolKitControl.CommandProvider.SendingCmdToLevBatteryViaB2BToolKit(LEVBatteryPackControl.Cmd_Battery_SetInfor.Cmd_SetOneWireTransmitOnce, new byte[] { 0x01 });
            //textBox6.Text = LEVUtilityLibrary.MassUtilities.ByteArrayToHexString(temp, true);

            string str = LEVUtilityLibrary.MassUtilities.StringTrim_Replace_EnterAndTab_CombineMultiSpaceToOne(textBox1.Text);
            temp = LEVUtilityLibrary.MassUtilities.HexStringToByteArray(str);
            LEVBatteryPackControl.LEVBPReceivedDataDetector rxDetector = new LEVBatteryPackControl.LEVBPReceivedDataDetector();
            List<LEVBatteryPackControl.LEVBPReceivedDataDetector.ReceivedPacket> listRxPocket = new List<LEVBatteryPackControl.LEVBPReceivedDataDetector.ReceivedPacket>();
            listRxPocket = rxDetector.DataDetector(temp);
            textBox6.AppendText("listRxPocket count = " + listRxPocket.Count + Environment.NewLine);
            textBox6.AppendText("=============================================" + Environment.NewLine);
            foreach (LEVBatteryPackControl.LEVBPReceivedDataDetector.ReceivedPacket pocket in listRxPocket)
            {
                textBox6.AppendText("group = " + pocket.Type + Environment.NewLine);
                textBox6.AppendText("cmd = " + String.Format("{0:X}", pocket.Cmd) + Environment.NewLine);
                string strData = LEVUtilityLibrary.MassUtilities.ByteArrayToHexString(pocket.Data, true);
                textBox6.AppendText("data = " + strData + Environment.NewLine);
                textBox6.AppendText("=============================================" + Environment.NewLine);
            }

            LEV_ST_G2_OneWireDataResolution ost = new LEV_ST_G2_OneWireDataResolution();
            dynamic dy = ost.GetItemInfor<LEV_ST_G2_OneWireDataResolution.ItemNameOfEepromData>(LEV_ST_G2_OneWireDataResolution.ItemNameOfEepromData.SystemSetting_Info_Byte1_Var_uchar_offset_96);
            //string[] stArr = Enum.GetNames(typeof(OneWireDataResolution.NameOfEepromData));
            //byte[] newArray = new byte[] { 0x3e, 0xbe, 0xa6, 0x72 };
            //byte[] newArray = new byte[] { 0x72, 0xa6, 0xbe, 0x3e };
            //float f = BitConverter.ToSingle(newArray, 0);
            byte[] newArray = new byte[] { 0xa0, 0x08 };
            int t = BitConverter.ToInt16(newArray, 0);
            byte a = 0xfe;
            sbyte b = unchecked((sbyte)a);
            textBox6.AppendText("=============================================" + b + Environment.NewLine);


            //ost.setOneWireData(OneWireDataResolution.OneWireDataGroup.SystemData, temp);
            //OneWireDataResolution.st_ItemInform[] stItems = ost.getAllOneWireData(typeof(OneWireDataResolution.ItemNameOfSystemStatus));
            //foreach (OneWireDataResolution.st_ItemInform item in stItems)
            //{
            //    textBox6.AppendText("===" + item.Name + "=" + item.Values + Environment.NewLine);
            //}
            //textBox6.AppendText("=============================================" + b + Environment.NewLine);
            //textBox6.AppendText("=============================================" + b + Environment.NewLine);
            //string[] stArr = Enum.GetNames(typeof(OneWireDataResolution.ItemNameOfSystemStatus));
            //int ItemIdx = 0;
            //foreach (string s in stArr)
            //{
            //    OneWireDataResolution.st_ItemInform item = ost.getOneWireData((OneWireDataResolution.ItemNameOfSystemStatus)ItemIdx);
            //    textBox6.AppendText("===" + item.Name + "=" + item.Values + Environment.NewLine);
            //    ItemIdx++;
            //}

            //ost.setOneWireData(OneWireDataResolution.OneWireDataGroup.EepromData, temp);
            //OneWireDataResolution.st_ItemInform[] stItems = ost.getAllOneWireData(typeof(OneWireDataResolution.ItemNameOfEepromData));
            //foreach (OneWireDataResolution.st_ItemInform item in stItems)
            //{
            //    textBox6.AppendText("===" + item.Name + "=" + item.Values + Environment.NewLine);
            //}
            //textBox6.AppendText("=============================================" + b + Environment.NewLine);
            //textBox6.AppendText("=============================================" + b + Environment.NewLine);
            //string[] stArr = Enum.GetNames(typeof(OneWireDataResolution.ItemNameOfEepromData));
            //int ItemIdx = 0;
            //foreach (string s in stArr)
            //{
            //    OneWireDataResolution.st_ItemInform item = ost.getOneWireData((OneWireDataResolution.ItemNameOfEepromData)ItemIdx);
            //    textBox6.AppendText("===" + item.Name + "=" + item.Values + "##" + Environment.NewLine);
            //    ItemIdx++;
            //} 
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string eof = "<EOF>";
            byte[] byteData = Encoding.UTF8.GetBytes("<EOF>"); //60,69,79, 70, 62
            byte[] source = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 22, 33, 44, 15, 16, 17, 18, 60, 69, 79, 70, 62, 0xff, 0xfe, 0xaa };
            byte[] compare = new byte[] {  44, 15, 16, };
            int idx = LEVUtilityLibrary.MassUtilities.ByteArrayIndexOf(source, compare);
            byte[] cpy = new byte[idx];
            Array.Copy(source, cpy, idx);
            string str = Encoding.UTF8.GetString(source, 0, source.Length);
            idx = str.IndexOf(eof);
            str = Encoding.ASCII.GetString(source, 0, source.Length);
            idx = str.IndexOf(eof);
            //textBox6.AppendText("=============================================" + b + Environment.NewLine);

        }

        private void Json_1_button_Click(object sender, EventArgs e)
        {
            Json_Org_textBox.Clear();
            Dictionary<string, int> original = new Dictionary<string, int>();
            original.Add("A", 1);
            original.Add("B", 2);
            /*序列化Dictionary物件*/
            string jsonStr = JsonConvert.SerializeObject(original, Formatting.None);
            /*Formatting.Indented，這樣的字串輸出在瀏覽器上檢視的話有排版效果較易閱讀*/
            //Json_Org_textBox.AppendText("Dictionary物件經過序列化：" + jsonStr + Environment.NewLine);
            Json_Org_textBox.AppendText( jsonStr + Environment.NewLine);
        }

        private void Json_2_button_Click(object sender, EventArgs e)
        {
            /*JSON字串反序列化為Dictionary物件*/
            //Dictionary<string, int> back = (Dictionary<string, int>)JsonConvert.DeserializeObject(Json_Org_textBox.Text, typeof(Dictionary<string, int>));
            Dictionary<string, int> back = JsonConvert.DeserializeObject<Dictionary<string, int>>(Json_Org_textBox.Text);
            foreach (string key in back.Keys)
            {
                Json_Parse_textBox.AppendText(key + "=>" + back[key] + Environment.NewLine);

            }
        }

        public enum LEV_Comm_Obj_Type : byte
        {
            LEV_B2B_App,
            LEV_B2C_App,
            LEV_Charger_Check_App
        }

        private class LEVCommObject
        {
            public string ObjName { get; set; }
            public LEV_Comm_Obj_Type ObjType { get; set; }
            public Object Obj;
        }

        private void J3_button_Click(object sender, EventArgs e)
        {
            Json_Org_textBox.Clear();
            List<string> ids = new List<string>() { "4", "8", "15", "16", "23", "42" };
            //string key = "score_update";

            LEVCommObject levobj_child = new LEVCommObject();
            levobj_child.ObjName = LEV_Comm_Obj_Type.LEV_B2C_App.ToString();
            levobj_child.ObjType = LEV_Comm_Obj_Type.LEV_B2C_App;
            levobj_child.Obj = ids;

            LEVCommObject levobj_Parent = new LEVCommObject();
            levobj_Parent.ObjName = LEV_Comm_Obj_Type.LEV_B2B_App.ToString();
            levobj_Parent.ObjType = LEV_Comm_Obj_Type.LEV_B2B_App;
            levobj_Parent.Obj = levobj_child;

            /*序列化Dictionary物件*/
            string jsonStr = JsonConvert.SerializeObject(levobj_Parent, Formatting.None);
            /*Formatting.Indented，這樣的字串輸出在瀏覽器上檢視的話有排版效果較易閱讀*/
            Json_Org_textBox.AppendText(jsonStr + Environment.NewLine);
        }

        private void J4_button_Click(object sender, EventArgs e)
        {
            /*JSON字串反序列化為Dictionary物件*/
            LEVCommObject back_L1 = (LEVCommObject)JsonConvert.DeserializeObject(Json_Org_textBox.Text, typeof(LEVCommObject));
            Json_Parse_textBox.AppendText("back_L1 : ObjName = " + back_L1.ObjName + Environment.NewLine);
            Json_Parse_textBox.AppendText("back_L1 : ObjType = " + back_L1.ObjType + Environment.NewLine);
            string backArrayStr = back_L1.Obj.ToString();

            LEVCommObject back_L2 = (LEVCommObject)JsonConvert.DeserializeObject(backArrayStr, typeof(LEVCommObject));
            Json_Parse_textBox.AppendText("back_L2 : ObjName = " + back_L2.ObjName + Environment.NewLine);
            Json_Parse_textBox.AppendText("back_L2 : ObjType = " + back_L2.ObjType + Environment.NewLine);

            backArrayStr = back_L2.Obj.ToString();
            List<string> strList = (List<string>)JsonConvert.DeserializeObject(backArrayStr, typeof(List<string>));
            foreach (string key in strList)
            {
                Json_Parse_textBox.AppendText("=>" + key + Environment.NewLine);

            }
        }
        private class LEVCommObject_test1
        {
            [JsonProperty]
            public string ObjName { get; set; }
            [JsonProperty]
            public LEV_Comm_Obj_Type ObjType { get; set; }
            [JsonProperty]
            public Dictionary<string, string> ParameterStrDict;
            [JsonProperty]
            public Dictionary<string, Object> ParameterObjDict;
            [JsonProperty]
            public Object extendParameterObj;
        }
        private class LEVCommObject_test1_chang
        {
            [JsonProperty]
            public string ObjName { get; set; }
            [JsonProperty]
            public string ObjName_more { get; set; }
            [JsonProperty]
            public LEV_Comm_Obj_Type ObjType { get; set; }
            [JsonProperty]
            public Dictionary<string, string> ParameterStrDict;
            [JsonProperty]
            public Dictionary<string, Object> ParameterObjDict;
            [JsonProperty]
            public Object extendParameterObj;
        }
        private void J5_button_Click(object sender, EventArgs e)
        {
            Json_Org_textBox.Clear();
            List<string> ids = new List<string>() { "4", "8", "15", "16", "23", "42" };
            //string key = "score_update";

            LEVCommObject_test1 levobj = new LEVCommObject_test1();
            levobj.ObjName = LEV_Comm_Obj_Type.LEV_B2C_App.ToString();
            levobj.ObjType = LEV_Comm_Obj_Type.LEV_B2C_App;
            Dictionary<string, Object> idsList = new Dictionary<string, Object>();
            idsList.Add("idsList1", ids);
            idsList.Add("idsList2", ids);
            idsList.Add("idsList3", ids);
            idsList.Add("idsList4", levobj);
            //levobj.ParameterObjDict = idsList;
            //levobj.Obj = ids;
            /*序列化Dictionary物件*/
            //string jsonStr = JsonConvert.SerializeObject(levobj, Formatting.None);
            string jsonStr = JsonConvert.SerializeObject(idsList, Formatting.None);
            /*Formatting.Indented，這樣的字串輸出在瀏覽器上檢視的話有排版效果較易閱讀*/
            Json_Org_textBox.AppendText(jsonStr + Environment.NewLine);

        }

        private void J6_button_Click(object sender, EventArgs e)
        {
            JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.All,
                TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
            };            
            /*JSON字串反序列化為Dictionary物件*/
            Dictionary<string, Object> back_L1 = JsonConvert.DeserializeObject < Dictionary<string, Object>>(Json_Org_textBox.Text);
            foreach (string key in back_L1.Keys)
            {
                Json_Parse_textBox.AppendText(key + "=>" + back_L1[key] + Environment.NewLine);
            }

            JArray a = JArray.FromObject(back_L1["idsList3"]);
            List<string> list = new List<string>();
            foreach (var item in a)
            {
                list.Add((string)item);
            }
            LEVCommObject_test1 back_L2 = JsonConvert.DeserializeObject<LEVCommObject_test1>(back_L1["idsList4"].ToString());

            JObject jobj = JObject.FromObject(back_L1["idsList4"]);
            JToken ageToken = jobj["ObjName"];

        }

        private void j7_button_Click(object sender, EventArgs e)
        {
            Json_Org_textBox.Clear();
            List<string> ids1 = new List<string>() { "14測試", "18", "215", "126", "223", "242" };
            List<string> ids = new List<string>() { "4", "8", "15", "16", "23", "42" };
            //string key = "score_update";

            LEVCommObject_test1 levobj = new LEVCommObject_test1();
            levobj.ObjName = LEV_Comm_Obj_Type.LEV_B2C_App.ToString();
            levobj.ObjType = LEV_Comm_Obj_Type.LEV_B2C_App;
            Dictionary<string, Object> idsList = new Dictionary<string, Object>();
            idsList.Add("c:/idsList.1", ids);
            idsList.Add("c:/idsList.2", ids1);
            idsList.Add("c:/idsList.3", ids);
            levobj.ParameterObjDict = idsList;

            Dictionary<string, string> idsStr = new Dictionary<string, string>();
            idsStr.Add("idsStr1", "t1測試");
            idsStr.Add("idsStr2", "t2測試");
            idsStr.Add("idsStr3", "t3測試");
            levobj.ParameterStrDict = idsStr;

            LEVCommObject_test1 levobj_c = new LEVCommObject_test1();
            levobj_c.ObjName = LEV_Comm_Obj_Type.LEV_Charger_Check_App.ToString();
            levobj_c.ObjType = LEV_Comm_Obj_Type.LEV_Charger_Check_App;
            levobj_c.ParameterStrDict = idsStr;
            levobj.extendParameterObj = levobj_c;
            /*序列化物件*/
            string jsonStr = JsonConvert.SerializeObject(levobj, Formatting.None);
            int len = jsonStr.Length;
            byte[] byteData = Encoding.UTF8.GetBytes(jsonStr);
            string s = Encoding.UTF8.GetString(byteData, 0, byteData.Length);
            //string jsonStr = JsonConvert.SerializeObject(levobj, Formatting.Indented);
            /*Formatting.Indented，這樣的字串輸出在瀏覽器上檢視的話有排版效果較易閱讀*/
            Json_Org_textBox.AppendText(jsonStr + Environment.NewLine);
        }

        private void j8_button_Click(object sender, EventArgs e)
        {
            /*JSON字串反序列化為LEVCommObject_test1物件*/
            LEVCommObject_test1_chang back = JsonConvert.DeserializeObject<LEVCommObject_test1_chang>(Json_Org_textBox.Text);
            Json_Parse_textBox.AppendText("back : ObjName = " + back.ObjName + Environment.NewLine);
            Json_Parse_textBox.AppendText("back : ObjType = " + back.ObjType + Environment.NewLine);


            /*轉換，原為LEVCommObject_test1: Dictionary<string, Object>物件*/
            JObject jobj = JObject.FromObject(back.ParameterObjDict);
            Dictionary<string, object> values = jobj.ToObject<Dictionary<string, object>>();
            foreach (var item in values)
            {
                Json_Parse_textBox.AppendText("dict =>" + item + Environment.NewLine);
            }
            if (values.ContainsKey("c:/idsList.2"))
            {
                Json_Parse_textBox.AppendText("dict content =>" + values["c:/idsList.2"] + Environment.NewLine);
                List<string> sList = jobj["c:/idsList.2"].ToObject<List<string>>();
                foreach (string s in sList)
                {
                    Json_Parse_textBox.AppendText("=>" + s + Environment.NewLine);
                }
            }

            /*轉換，原為LEVCommObject_test1: Dictionary<string, string>物件*/
            jobj = JObject.FromObject(back.ParameterStrDict);
            Dictionary<string, string> val = jobj.ToObject<Dictionary<string, string>>();
            foreach (var s in val)
            {
                Json_Parse_textBox.AppendText("dict =>" + s + Environment.NewLine);
            }

            /*轉換，原為LEVCommObject_test1: Object extendParameterOb物件, set 為LEVCommObject_test1 Type*/
            jobj = JObject.FromObject(back.extendParameterObj);
            LEVCommObject_test1_chang levC_Obj = jobj.ToObject<LEVCommObject_test1_chang>();
            Json_Parse_textBox.AppendText("back child : ObjName = " + levC_Obj.ObjName + Environment.NewLine);
            Json_Parse_textBox.AppendText("back child: ObjType = " + levC_Obj.ObjType + Environment.NewLine);
            /*轉換，原為LEVCommObject_test1: Dictionary<string, string>物件*/
            jobj = JObject.FromObject(levC_Obj.ParameterStrDict);
            Dictionary<string, string> levC_val = jobj.ToObject<Dictionary<string, string>>();
            foreach (var s in levC_val)
            {
                Json_Parse_textBox.AppendText("dict =>" + s + Environment.NewLine);
            }
            Json_Parse_textBox.AppendText("test =>" + levC_Obj.ObjName_more + Environment.NewLine);

        }

        private void j9_button_Click(object sender, EventArgs e)
        {
            Json_Org_textBox.Clear();
            List<string> ids1 = new List<string>() { "14測試", "18", "215", "126", "223", "242" };
            List<string> ids = new List<string>() { "4", "8", "15", "16", "23", "42" };
            //string key = "score_update";

            LEVCommObject_test1 levobj = new LEVCommObject_test1();
            levobj.ObjName = LEV_Comm_Obj_Type.LEV_B2C_App.ToString();
            levobj.ObjType = LEV_Comm_Obj_Type.LEV_B2C_App;
            Dictionary<string, Object> idsList = new Dictionary<string, Object>();
            idsList.Add("c:/idsList.1", ids);
            idsList.Add("c:/idsList.2", ids1);
            idsList.Add("c:/idsList.3", ids);
            levobj.ParameterObjDict = idsList;

            Dictionary<string, string> idsStr = new Dictionary<string, string>();
            idsStr.Add("idsStr1", "t1測試");
            idsStr.Add("idsStr2", "t2測試");
            idsStr.Add("idsStr3", "t3測試");
            levobj.ParameterStrDict = idsStr;

            LEVCommObject_test1 levobj_c = new LEVCommObject_test1();
            levobj_c.ObjName = LEV_Comm_Obj_Type.LEV_Charger_Check_App.ToString();
            levobj_c.ObjType = LEV_Comm_Obj_Type.LEV_Charger_Check_App;
            levobj_c.ParameterStrDict = idsStr;
            levobj.extendParameterObj = levobj_c;

            /*Bson序列化物件*/
            var memoryStream = new MemoryStream();
            BsonWriter bsonWriter = new BsonWriter(memoryStream);
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(bsonWriter, levobj);
            //var res = string.Format(BitConverter.ToString(memoryStream.ToArray()));
            byte[] bsonData = memoryStream.ToArray();
            var res = string.Format(BitConverter.ToString(bsonData));
            //var res = BitConverter.ToString(bsonData);
            Json_Org_textBox.AppendText(res + Environment.NewLine);
        }
        private byte[] StringToBytes(string str)
        {
            str = str.Trim();
            String[] arr = str.Split('-');
            byte[] array = new byte[arr.Length];
            for (int i = 0; i < arr.Length; i++) array[i] = Convert.ToByte(arr[i], 16);
            return array;
        }
        private void j10_button_Click(object sender, EventArgs e)
        {
             /*BSON字串反序列化為LEVCommObject_test1物件*/
            var memoryStream = new MemoryStream(StringToBytes(Json_Org_textBox.Text));
            BsonReader reader = new BsonReader(memoryStream);
           JsonSerializer serializer = new JsonSerializer();
            LEVCommObject_test1 back = serializer.Deserialize<LEVCommObject_test1>(reader);
            //LEVCommObject_test1 back = JsonConvert.DeserializeObject<LEVCommObject_test1>(Json_Org_textBox.Text);
            Json_Parse_textBox.AppendText("back : ObjName = " + back.ObjName + Environment.NewLine);
            Json_Parse_textBox.AppendText("back : ObjType = " + back.ObjType + Environment.NewLine);


            /*轉換，原為LEVCommObject_test1: Dictionary<string, Object>物件*/
            JObject jobj = JObject.FromObject(back.ParameterObjDict);
            Dictionary<string, object> values = jobj.ToObject<Dictionary<string, object>>();
            foreach (var item in values)
            {
                Json_Parse_textBox.AppendText("dict =>" + item + Environment.NewLine);
            }
            if (values.ContainsKey("c:/idsList.2"))
            {
                Json_Parse_textBox.AppendText("dict content =>" + values["c:/idsList.2"] + Environment.NewLine);
                List<string> sList = jobj["c:/idsList.2"].ToObject<List<string>>();
                foreach (string s in sList)
                {
                    Json_Parse_textBox.AppendText("=>" + s + Environment.NewLine);
                }
            }

            /*轉換，原為LEVCommObject_test1: Dictionary<string, string>物件*/
            jobj = JObject.FromObject(back.ParameterStrDict);
            Dictionary<string, string> val = jobj.ToObject<Dictionary<string, string>>();
            foreach (var s in val)
            {
                Json_Parse_textBox.AppendText("dict =>" + s + Environment.NewLine);
            }

            /*轉換，原為LEVCommObject_test1: Object extendParameterOb物件, set 為LEVCommObject_test1 Type*/
            jobj = JObject.FromObject(back.extendParameterObj);
            LEVCommObject_test1 levC_Obj = jobj.ToObject<LEVCommObject_test1>();
            Json_Parse_textBox.AppendText("back child : ObjName = " + levC_Obj.ObjName + Environment.NewLine);
            Json_Parse_textBox.AppendText("back child: ObjType = " + levC_Obj.ObjType + Environment.NewLine);
            /*轉換，原為LEVCommObject_test1: Dictionary<string, string>物件*/
            jobj = JObject.FromObject(levC_Obj.ParameterStrDict);
            Dictionary<string, string> levC_val = jobj.ToObject<Dictionary<string, string>>();
            foreach (var s in levC_val)
            {
                Json_Parse_textBox.AppendText("dict =>" + s + Environment.NewLine);
            }
        }
        private class LEVCommObject_test2
        {
            [JsonProperty]
            public string ObjName { get; set; }
            [JsonProperty]
            public LEV_Comm_Obj_Type ObjType { get; set; }
            [JsonProperty]
            public Dictionary<string, string> ParameterStrDict;
            [JsonProperty]
            public Dictionary<string, Object> ParameterObjDict;
            [JsonProperty]
            public Dictionary<string, string> ParameterImageDict;   //key:image file name, value:image description 
            [JsonProperty]
            public Dictionary<string, byte[]> ParameterImageBodyDict;   //key:image file name, value: byte[]image body content 
            [JsonProperty]
            public Object extendParameterObj;
        }
        private void j11_button_Click(object sender, EventArgs e)
        {
            //string imageFile = Path.Combine(Environment.CurrentDirectory, "pic.png");
            string imageFile = Path.Combine(Environment.CurrentDirectory, "small.jpg");

            //Read file to byte array
            FileStream stream = File.OpenRead(imageFile);
            byte[] fileBytes = new byte[stream.Length];
            stream.Read(fileBytes, 0, fileBytes.Length);
            stream.Close();

            Json_Org_textBox.Clear();
            /*create 物件*/
            LEVCommObject_test2 levobj = new LEVCommObject_test2();
            levobj.ObjName = LEV_Comm_Obj_Type.LEV_B2C_App.ToString();
            levobj.ObjType = LEV_Comm_Obj_Type.LEV_B2C_App;
            Dictionary<string, string> imageStr = new Dictionary<string, string>();
            imageStr.Add("image", "image圖片測試");
            levobj.ParameterImageDict = imageStr;
            Dictionary<string, byte[]> imageBody = new Dictionary<string, byte[]>();
            imageBody.Add("image", fileBytes);
            levobj.ParameterImageBodyDict = imageBody;
            /*序列化物件*/
            string jsonStr = JsonConvert.SerializeObject(levobj, Formatting.None);
            /*Formatting.Indented，這樣的字串輸出在瀏覽器上檢視的話有排版效果較易閱讀*/
            //string jsonStr = JsonConvert.SerializeObject(levobj, Formatting.Indented);
            int len = jsonStr.Length;
            byte[] byteData = Encoding.UTF8.GetBytes(jsonStr);
            string s = Encoding.UTF8.GetString(byteData, 0, byteData.Length);
            Json_Org_textBox.AppendText(jsonStr + Environment.NewLine);

        }

        private void j12_button_Click(object sender, EventArgs e)
        {
            /*JSON字串反序列化為LEVCommObject_test2物件*/
            LEVCommObject_test2 back = JsonConvert.DeserializeObject<LEVCommObject_test2>(Json_Org_textBox.Text);
            Json_Parse_textBox.AppendText("back : ObjName = " + back.ObjName + Environment.NewLine);
            Json_Parse_textBox.AppendText("back : ObjType = " + back.ObjType + Environment.NewLine);

            /*轉換，原為LEVCommObject_test2: Dictionary<string, string>物件*/
            JObject jobj = JObject.FromObject(back.ParameterImageDict);
            Dictionary<string, string> val = jobj.ToObject<Dictionary<string, string>>();
            foreach (var s in val)
            {
                Json_Parse_textBox.AppendText("image dict =>" + s + Environment.NewLine);
            }
            /*轉換，原為LEVCommObject_test2: Dictionary<string, byte[]>物件*/
            jobj = JObject.FromObject(back.ParameterImageBodyDict);
            Dictionary<string, byte[]> values = jobj.ToObject<Dictionary<string, byte[]>>();
            byte[] body = new byte[]{0};
            if (values.ContainsKey("image"))
            {
                body = jobj["image"].ToObject<byte[]>();
            }

            //Begins the process of writing the byte array back to a file
            //string imageFile = Path.Combine(Environment.CurrentDirectory, "pic_test.png");
            string imageFile = Path.Combine(Environment.CurrentDirectory, "small_test.jpg");
            using (Stream file = File.OpenWrite(imageFile))
            {
                file.Write(body, 0, body.Length);
            }
        }

        private void b13_button_Click(object sender, EventArgs e)
        {
            //string imageFile = Path.Combine(Environment.CurrentDirectory, "pic.png");
            string imageFile = Path.Combine(Environment.CurrentDirectory, "small.jpg");

            //Read file to byte array
            FileStream stream = File.OpenRead(imageFile);
            byte[] fileBytes = new byte[stream.Length];
            stream.Read(fileBytes, 0, fileBytes.Length);
            stream.Close();

            Json_Org_textBox.Clear();
            /*create 物件*/
            LEVCommObject_test2 levobj = new LEVCommObject_test2();
            levobj.ObjName = LEV_Comm_Obj_Type.LEV_B2C_App.ToString();
            levobj.ObjType = LEV_Comm_Obj_Type.LEV_B2C_App;
            Dictionary<string, string> imageStr = new Dictionary<string, string>();
            imageStr.Add("image", "image圖片測試");
            levobj.ParameterImageDict = imageStr;
            Dictionary<string, byte[]> imageBody = new Dictionary<string, byte[]>();
            imageBody.Add("image", fileBytes);
            levobj.ParameterImageBodyDict = imageBody;

            /*Bson序列化物件*/
            var memoryStream = new MemoryStream();
            BsonWriter bsonWriter = new BsonWriter(memoryStream);
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(bsonWriter, levobj);
            //var res = string.Format(BitConverter.ToString(memoryStream.ToArray()));
            byte[] bsonData = memoryStream.ToArray();
            var res = string.Format(BitConverter.ToString(bsonData));
            Json_Org_textBox.AppendText(res + Environment.NewLine);

        }

        private void b14_button_Click(object sender, EventArgs e)
        {
            /*BSON字串反序列化為LEVCommObject_test1物件*/
            var memoryStream = new MemoryStream(StringToBytes(Json_Org_textBox.Text));
            BsonReader reader = new BsonReader(memoryStream);
            JsonSerializer serializer = new JsonSerializer();
            LEVCommObject_test2 back = serializer.Deserialize<LEVCommObject_test2>(reader);
            //LEVCommObject_test2 back = JsonConvert.DeserializeObject<LEVCommObject_test2>(Json_Org_textBox.Text);
            Json_Parse_textBox.AppendText("back : ObjName = " + back.ObjName + Environment.NewLine);
            Json_Parse_textBox.AppendText("back : ObjType = " + back.ObjType + Environment.NewLine);

            /*轉換，原為LEVCommObject_test2: Dictionary<string, string>物件*/
            JObject jobj = JObject.FromObject(back.ParameterImageDict);
            Dictionary<string, string> val = jobj.ToObject<Dictionary<string, string>>();
            foreach (var s in val)
            {
                Json_Parse_textBox.AppendText("image dict =>" + s + Environment.NewLine);
            }
            /*轉換，原為LEVCommObject_test2: Dictionary<string, byte[]>物件*/
            jobj = JObject.FromObject(back.ParameterImageBodyDict);
            Dictionary<string, byte[]> values = jobj.ToObject<Dictionary<string, byte[]>>();
            byte[] body = new byte[] { 0 };
            if (values.ContainsKey("image"))
            {
                body = jobj["image"].ToObject<byte[]>();
            }

            //Begins the process of writing the byte array back to a file
            //string imageFile = Path.Combine(Environment.CurrentDirectory, "pic_test.png");
            string imageFile = Path.Combine(Environment.CurrentDirectory, "small_test.jpg");
            using (Stream file = File.OpenWrite(imageFile))
            {
                file.Write(body, 0, body.Length);
            }
        }
        private class LEVCommObject_J7_1
        {
            public const string str = "testttt";
            public static string getStr()
            {
                return str;
            }
            public enum LEV_Comm_Obj_Type_Test : byte
            {
                LEV_B2B_App,
                LEV_B2C_App,
                LEV_Charger_Check_App
            }
            [JsonProperty]
            public string ObjNameStr = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            [JsonProperty]
            //public Version ver = Assembly.GetExecutingAssembly().GetName().Version;
            public Version ver = new Version(2,4,5,20140505);
            [JsonProperty]
            public string ObjName { get; set; }
            [JsonProperty]
            public string ObjName_more { get; set; }
            [JsonProperty]
            public int ObjInt { get; set; }
            [JsonProperty]
            public LEV_Comm_Obj_Type ObjType { get; set; }
            [JsonProperty]
            public Dictionary<string, string> ParameterStrDict;
            [JsonProperty]
            public Dictionary<string, Object> ParameterObjDict;
            [JsonProperty]
            public Object extendParameterObj;
            [JsonProperty]
            public LEVCommObject_J7_1 classObj;

        }
        private class LEVCommObject_J7_1_chang
        {
            [JsonProperty]
            public string ObjName { get; set; }
            [JsonProperty]
            public string ObjName_more { get; set; }
            [JsonProperty]
            public int ObjInt { get; set; }
            [JsonProperty]
            public Version ver = Assembly.GetExecutingAssembly().GetName().Version;
            [JsonProperty]
            public LEV_Comm_Obj_Type ObjType { get; set; }
            [JsonProperty]
            public Dictionary<string, string> ParameterStrDict;
            [JsonProperty]
            public Dictionary<string, Object> ParameterObjDict;
            [JsonProperty]
            public Object extendParameterObj;
            [JsonProperty]
            public Object extendParameterObj1;
        }

        private void J7_1_button_Click(object sender, EventArgs e)
        {
            Json_Org_textBox.Clear();
            List<string> ids1 = new List<string>() { "14測試", "18", "215", "126", "223", "242" };
            List<string> ids = new List<string>() { "4", "8", "15", "16", "23", "42" };
            //string key = "score_update";

            LEVCommObject_J7_1 levobj = new LEVCommObject_J7_1();
            levobj.ObjName = LEV_Comm_Obj_Type.LEV_B2C_App.ToString();
            levobj.ObjType = LEV_Comm_Obj_Type.LEV_B2C_App;
            Dictionary<string, Object> idsList = new Dictionary<string, Object>();
            idsList.Add("c:/idsList.1", ids);
            idsList.Add("c:/idsList.2", ids1);
            idsList.Add("c:/idsList.3", ids);
            levobj.ParameterObjDict = idsList;

            Dictionary<string, string> idsStr = new Dictionary<string, string>();
            idsStr.Add("idsStr1", "t1測試");
            idsStr.Add("idsStr2", "t2測試");
            idsStr.Add("idsStr3", "t3測試");
            levobj.ParameterStrDict = idsStr;

            LEVCommObject_J7_1 levobj_c = new LEVCommObject_J7_1();
            levobj_c.ObjName = LEV_Comm_Obj_Type.LEV_Charger_Check_App.ToString();
            levobj_c.ObjType = LEV_Comm_Obj_Type.LEV_Charger_Check_App;
            levobj_c.ParameterStrDict = idsStr;
            levobj.extendParameterObj = levobj_c;
            /*序列化物件*/
            string jsonStr = JsonConvert.SerializeObject(levobj, Formatting.None);
            int len = jsonStr.Length;
            byte[] byteData = Encoding.UTF8.GetBytes(jsonStr);
            string s = Encoding.UTF8.GetString(byteData, 0, byteData.Length);
            //string jsonStr = JsonConvert.SerializeObject(levobj, Formatting.Indented);
            /*Formatting.Indented，這樣的字串輸出在瀏覽器上檢視的話有排版效果較易閱讀*/
            Json_Org_textBox.AppendText(jsonStr + Environment.NewLine);

        }

        private void J8_1_button_Click(object sender, EventArgs e)
        {
            /*JSON字串反序列化為LEVCommObject_test1物件*/
            LEVCommObject_J7_1_chang back = JsonConvert.DeserializeObject<LEVCommObject_J7_1_chang>(Json_Org_textBox.Text);
            Json_Parse_textBox.AppendText("back : ObjName = " + back.ObjName + Environment.NewLine);
            Json_Parse_textBox.AppendText("back : ObjType = " + back.ObjType + Environment.NewLine);
            Json_Parse_textBox.AppendText("back : ObjName more = " + back.ObjName_more + Environment.NewLine);
            Json_Parse_textBox.AppendText("back : ObjInt = " + back.ObjInt + Environment.NewLine);


            /*轉換，原為LEVCommObject_test1: Dictionary<string, Object>物件*/
            JObject jobj = JObject.FromObject(back.ParameterObjDict);
            Dictionary<string, object> values = jobj.ToObject<Dictionary<string, object>>();
            foreach (var item in values)
            {
                Json_Parse_textBox.AppendText("dict =>" + item + Environment.NewLine);
            }
            if (values.ContainsKey("c:/idsList.2"))
            {
                Json_Parse_textBox.AppendText("dict content =>" + values["c:/idsList.2"] + Environment.NewLine);
                List<string> sList = jobj["c:/idsList.2"].ToObject<List<string>>();
                foreach (string s in sList)
                {
                    Json_Parse_textBox.AppendText("=>" + s + Environment.NewLine);
                }
            }

            /*轉換，原為LEVCommObject_test1: Dictionary<string, string>物件*/
            jobj = JObject.FromObject(back.ParameterStrDict);
            Dictionary<string, string> val = jobj.ToObject<Dictionary<string, string>>();
            foreach (var s in val)
            {
                Json_Parse_textBox.AppendText("dict =>" + s + Environment.NewLine);
            }

            /*轉換，原為LEVCommObject_test1: Object extendParameterOb物件, set 為LEVCommObject_test1 Type*/
            jobj = JObject.FromObject(back.extendParameterObj);
            LEVCommObject_J7_1_chang levC_Obj = jobj.ToObject<LEVCommObject_J7_1_chang>();
            Json_Parse_textBox.AppendText("back child : ObjName = " + levC_Obj.ObjName + Environment.NewLine);
            Json_Parse_textBox.AppendText("back child: ObjType = " + levC_Obj.ObjType + Environment.NewLine);
            /*轉換，原為LEVCommObject_test1: Dictionary<string, string>物件*/
            jobj = JObject.FromObject(levC_Obj.ParameterStrDict);
            Dictionary<string, string> levC_val = jobj.ToObject<Dictionary<string, string>>();
            foreach (var s in levC_val)
            {
                Json_Parse_textBox.AppendText("dict =>" + s + Environment.NewLine);
            }
            Json_Parse_textBox.AppendText("test =>" + levC_Obj.ObjName_more + Environment.NewLine);
            Json_Parse_textBox.AppendText("test =>" + levC_Obj.extendParameterObj1 + Environment.NewLine);
            /*轉換，原為LEVCommObject_test1: Version 物件*/
            jobj = JObject.FromObject(levC_Obj.ver);
            Version ver = jobj.ToObject<Version>();
            Json_Parse_textBox.AppendText("version =>" + ver + Environment.NewLine);

        }

    }
}
